package de.datenwalze.winterpokal;

import de.datenwalze.winterpokal.http.WPHttpConnection;
import de.datenwalze.winterpokal.json.WPEntry;
import de.datenwalze.winterpokal.json.WPJsonResponse;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class EntryActivity extends Activity implements OnClickListener {

	private Spinner spinner;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.entry);

		spinner = (Spinner) findViewById(R.id.spinnerSportart);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.sportarten, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new SportartenOnItemSelectedListener());
	}

	public void onClickSendEntry(View v) {
		// Send the stuff
		WPEntry wpEntry = new WPEntry();
		wpEntry.setCategory(spinner.getSelectedItem().toString());
		DatePicker datePicker = (DatePicker) findViewById(R.id.datePickerEntry);
		wpEntry.setDate(String.format("%s-%s-%s", datePicker.getYear(),
				datePicker.getMonth() + 1, datePicker.getDayOfMonth()));
		
		TimePicker timePicker = (TimePicker) findViewById(R.id.timePickerEntry);
		int hours = timePicker.getCurrentHour() % 12;
		int minutes = timePicker.getCurrentMinute();
		wpEntry.setDuration(String.valueOf((hours*60)+minutes));
		
		EditText descriptionEditText = (EditText) findViewById(R.id.editTextDescription);
		
		wpEntry.setDescription(descriptionEditText.getText().toString());
		
		WPJsonResponse jsonResponse = WPHttpConnection.sendEntry(wpEntry);
		
		Toast.makeText(getApplicationContext(), jsonResponse.getStatus(), Toast.LENGTH_LONG);
	}

	public class SportartenOnItemSelectedListener implements
			OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {

			Toast.makeText(
					parent.getContext(),
					"Sportart ist: " + parent.getItemAtPosition(pos).toString(),
					Toast.LENGTH_LONG).show();
		}

		public void onNothingSelected(AdapterView parent) {
			// Do nothing.
		}
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		Log.i("ENTRY", "Entry activity on click is not impleneted.");
	}
}
